<?php
namespace app\index\logic;

use app\common\logic\LogicBase;

class Open extends LogicBase
{
    public function wechatNotify()
    {
        try {
            $orderNo = get_order_sn();
            if (empty($orderNo)) {
                return $this->buildWxXml('FAIL', 'order_no parse fail');
            }

            $data = $this->servicePay->driverWxpay->notify();
            if (!$data) {
                return $this->buildWxXml('FAIL', 'notify sign fail');
            }

            $transactionId = $data['transaction_id'] ?? '';
            $result = $this->logicVip->paymentSuccess(['order_no' => $orderNo, 'transaction_id' => $transactionId]);

            if (is_array($result) && isset($result[0]) && $result[0] === RESULT_SUCCESS) {
                return $this->buildWxXml('SUCCESS', 'OK');
            }
            $msg = is_array($result) && isset($result[1]) ? $result[1] : 'process fail';
            return $this->buildWxXml('FAIL', $msg);
        } catch (\Throwable $e) {
            return $this->buildWxXml('FAIL', 'exception');
        }
    }

    private function buildWxXml($code, $msg)
    {
        return '<xml><return_code><![CDATA[' . $code . ']]></return_code><return_msg><![CDATA[' . $msg . ']]></return_msg></xml>';
    }
}

